<?php

namespace App\Master\POST;

/**
 * 提交内容
 */
class Article extends \App\Master\CheckUser {

    /**
     * 发表日志
     */
    public function action() {
        $data['timelog_title'] = $this->isP('title', '请填写标题');
        $content = $this->isP('content', '请填写内容');
        $data['timelog_type'] = $this->isP('type', '请选择类型');
        $data['user_id'] = $_SESSION['user']['user_id'];
        $data['timelog_updatetime'] = $data['timelog_createtime'] = time();
        $data['timelog_delete'] = '0';

        $this->db()->transaction();
        $baseInsert = $this->db('timelog')->insert($data);
        if ($baseInsert === false) {
            $this->db()->rollBack();
            $this->error('创建时间日志出错');
        }

        $updateUserCount = $this->db()->query("UPDATE {$this->prefix}user SET user_timelog = user_timelog + 1 WHERE user_id = :user_id", array('user_id' => $_SESSION['user']['user_id']));
        if ($updateUserCount === false) {
            $this->db()->rollBack();
            $this->error('更新计数出错');
        }

        $addContent = $this->db('timelog_content')->insert(array('timelog_id' => $baseInsert, 'user_id' => $data['user_id'], 'timelog_content' => $content, 'timelog_content_createtime' => $data['timelog_createtime']));
        if ($addContent === false) {
            $this->db()->rollBack();
            $this->error('添加时间日志层数出错');
        }

        $this->db()->commit();

        $this->success('发表时间日志成功!', $this->url('Master-Article-view', ['id' => $baseInsert]));
    }

    /**
     * 添加新内容
     */
    public function addContent() {
        $id = $this->isG('id', '丢失日志');
        $content = $this->isP('content', '请填写内容');

        $checkUser = $this->db('timelog')->where("user_id = :user_id AND timelog_id = :timelog_id AND timelog_delete = 0")->find(array('user_id' => $_SESSION['user']['user_id'], 'timelog_id' => $id));

        if (empty($checkUser)) {
            $this->error('您没有操作本日志的权限');
        }

        $this->db()->transaction();
        $time = time();
        $updateTime = $this->db()->query("UPDATE {$this->prefix}timelog SET timelog_updatetime = '{$time}' WHERE timelog_id = :timelog_id ", array('timelog_id' => $id));
        if ($updateTime === FALSE) {
            $this->db()->rollBack();
            $this->error('更新日志时间出错');
        }

        $addContent = $this->db('timelog_content')->insert(array('timelog_id' => $id, 'user_id' => $_SESSION['user']['user_id'], 'timelog_content' => $content, 'timelog_content_createtime' => $time));
        if ($addContent === FALSE) {
            $this->db()->rollBack();
            $this->error('添加内容时出错');
        }

        $this->db()->commit();
        $this->success('添加内容成功!', $this->url('Master-Article-view', ['id' => $id]));
    }

    /**
     * 添加新评论
     */
    public function addComment() {
        $id = $this->isP('id', '丢失日志');
        $comment = $this->isP('comment', '请填写内容');

        $atResult = $this->atregex($comment);
        if ($atResult !== false) {
            $comment = $atResult['comment'];
            $atUser = $atResult['atUser'];
        }

        $check = \Model\Content::findContent('timelog', $id, 'timelog_id');
        if (empty($check) || $check['timelog_delete'] === '1') {
            $this->error('该时间日志不存在或者被删除');
        }

        $this->db()->transaction();

        $updateComment = $this->db()->query("UPDATE {$this->prefix}timelog SET timelog_comment_num = timelog_comment_num + 1 WHERE timelog_id = :timelog_id", array('timelog_id' => $id));
        if ($updateComment === false) {
            $this->db()->rollBack();
            $this->error('更新评论数出错');
        }

        $findFloor = $this->db('timelog_comment')->field('timelog_comment_floor')->where('timelog_id = :timelog_id')->order('timelog_comment_time DESC')->find([
            'timelog_id' => $id
        ]);

        $addComment = $this->db('timelog_comment')->insert([
            'timelog_id' => $id,
            'user_id' => $_SESSION['user']['user_id'],
            'timelog_comment' => $comment,
            'timelog_comment_time' => time(),
            'timelog_comment_floor' => empty($findFloor['timelog_comment_floor']) ? '1' : $findFloor['timelog_comment_floor'] + 1
        ]);
        if ($addComment === FALSE) {
            $this->db()->rollBack();
            $this->error('添加评论时出错');
        }

        if (!empty($atUser)) {
            //添加艾特提醒
            foreach ($atUser as $userId) {
                $createTips = $this->db('user_tips')->insert([
                    'timelog_id' => $id,
                    'send_user_id' => $_SESSION['user']['user_id'],
                    'accept_user_id' => $userId,
                    'comment_id' => $addComment,
                    'tips_time' => time(),
                    'tips_status' => '0',
                    'tips_type' => '0'
                ]);
                if ($createTips === FALSE) {
                    $this->db()->rollBack();
                    $this->error('生成评论消息提示出错');
                }
            }
        }

        //添加回复提醒
        $this->db('user_tips')->insert([
            'timelog_id' => $id,
            'send_user_id' => $_SESSION['user']['user_id'],
            'accept_user_id' => $check['user_id'],
            'comment_id' => $addComment,
            'tips_time' => time(),
            'tips_status' => '0',
            'tips_type' => '1'
        ]);

        $this->db()->commit();
        $this->success('添加评论成功!', $this->url('Master-Article-view', ['id' => $id]));
    }

    /**
     * 正则匹配at提示用户
     * @param type $comment 评论内容
     * @return boolean 不存在则返回false。反之返回处理好的评论和对应的用户ID
     */
    private function atregex($comment) {
        preg_match_all("/@.*?\S+/i", $comment, $matches);
        if (empty($matches['0'])) {
            return false;
        }

        $atUser = array();

        foreach (array_unique($matches['0']) as $key => $value) {

            $userName = substr($value, 1);

            $userInfo = \Model\Content::findContent('user', $userName, 'user_name');
            if (empty($userInfo)) {
                continue;
            }

            $comment = str_replace("{$value} ", htmlspecialchars('<a href="' . $this->url('Master-Article-user', ['id' => $userInfo['user_id']]) . '" class="atuser">' . $value . '</a>'), $comment);

            $atUser[$userInfo['user_id']] = $userInfo['user_id'];
        }

        if (empty($atUser)) {
            return false;
        }


        return array('atUser' => $atUser, 'comment' => $comment);
    }

}
